package com.leetcode.problems005;


/**
 * @Description
 * @Date 2021/11/20 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    class Tuple3{
        public int left;
        public int right;
        public int len;
        public Tuple3(int left,int right){
            this.left = left;
            this.right = right;
            this.len = right - left + 1;
        }
    }
    /**
     *s[i,j]区间内是否为回文字符串
     */
    public String longestPalindrome(String s) {
        if(s == null || s.length() <= 1){
            return s;
        }
        Tuple3 maxRes = new Tuple3(0,0);
        for (int i = 0; i < s.length(); i++) {
            //以i为中心检查，两边的元素是否符合回文字符串
            Tuple3 len1 = checkAroundByIndex(s, i, i);
            Tuple3 len2 = checkAroundByIndex(s, i, i + 1);
            Tuple3 tem = len1;
            if(len1.len < len2.len){
                tem = len2;
            }
            if(maxRes.len < tem.len){
                maxRes = tem;
            }
        }

        return s.substring(maxRes.left, maxRes.right+1);
    }

    public Tuple3 checkAroundByIndex(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return new Tuple3(left+1,right-1);
    }

    public static void main(String[] args) {
        System.out.println(new Solution().longestPalindrome("babad"));
    }
}
